package model

import (
	"strings"
)

type coinModel struct {}

const (
	CoinStatusEnable = 1
)

var CoinModel = new(coinModel)

// 修改
func (m *coinModel) UpdateCoin(mid int, coin *Coin) (bool, error) {
	rows, err := MainDB.Where("mid=?", mid).
		Cols("max_supply", "circulating_supply", "date_added").Update(coin)
		if err != nil {
			return false, err
		}
		return rows > 0, err
}

// 获取所有币种
func (m *coinModel) FindAll() ([]*Coin, error) {
	var coins []*Coin
	err := MainDB.Where("enable=?", CoinStatusEnable).Find(&coins)
	if err != nil {
		return nil, err
	}
	return coins, nil
}


// 获取所有币种
func (m *coinModel) All() ([]*Coin, error) {
	var coins []*Coin
	err := MainDB.Find(&coins)
	if err != nil {
		return nil, err
	}
	return coins, nil
}

// 获取一条记录
func (m *coinModel) GetItemBySymbol(symbol string) (*Coin, error) {
	var coin Coin
	_, err := MainDB.Where("symbol=?", symbol).Where("enable=?", CoinStatusEnable).Get(&coin)
	if err !=  nil {
		return nil, err
	}
	return &coin, nil
}

// 按关键字查找
func (m *coinModel) SearchByKeyWord(keyword string) ([]*Coin, error) {
	var coins []*Coin
	err := MainDB.
		/*
		Where("enable=?", CoinStatusEnable).
		Where("symbol like ?", "%" + strings.ToUpper(keyword) + "%").
		Or("name_cn like ?", "%" + strings.ToUpper(keyword) + "%").
		Or("name_en like ?", "%" + strings.ToUpper(keyword) + "%").
		*/
		SQL("select * from coin where enable=? and (symbol like ? or name_cn like ? or name_en like ?)",
			CoinStatusEnable, strings.ToUpper(keyword) + "%", strings.ToUpper(keyword) + "%", strings.ToUpper(keyword) + "%").
		Find(&coins)
	if err != nil {
		return nil, err
	}

	return coins, nil
}

// 插入数据
func (m *coinModel) InsertMulti(datas []*Coin) (bool, error) {
	items, err := MainDB.Insert(datas)
	if err != nil {
		return false, err
	}
	return items > 0, nil
}